package com.lines.chap03;

/**
 * <p>
 * <code>MyLinkedList</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-28 15:37
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class MyLinkedList {
    private Node head;

    public void insertHead(int data){
        Node node = new Node(data);
        node.next = head;
        head = node;
    }

    public void insertNth(int data,int pos){
        if (pos == 0){
            insertHead(data);
        }else {
            Node newNode = new Node(data);
            Node node = head;
            for (int i = 1; i < pos; i++) {
                node = node.next;
            }
            newNode.next = node.next;
            node.next = newNode;
        }
    }

    public void deleteHead(){
        head = head.next;
    }

    public void deleteNth(int pos){
        if (pos==0){
            deleteHead();
        }else {
            Node node = head;
            for (int i = 1; i < pos; i++) {
                node = node.next;
            }
            node.next = node.next.next;
        }
    }

    public void print(){
        Node cur = head;
        while (cur!=null){
            System.out.print(cur.value+" ");
            cur = cur.next;
        }
        System.out.println();
    }

    public Node find(int data){
        Node cur = head;
        while (cur!=null){
            if (data==cur.value){
                return cur;
            }
            cur = cur.next;
        }
        return  null;
    }

    public static void main(String[] args) {
        MyLinkedList linkedList = new MyLinkedList();
        linkedList.insertHead(0);
        linkedList.insertHead(1);
        linkedList.insertHead(3);
        linkedList.insertHead(4);
        linkedList.insertHead(2);
        linkedList.print();
        System.out.println("=======================");
        linkedList.insertNth(99,3);
        linkedList.print();
        System.out.println("=======================");
        linkedList.insertNth(88,6);
        linkedList.print();
        System.out.println("=======================");
        linkedList.deleteHead();
        linkedList.print();
        System.out.println("=======================");
        linkedList.deleteNth(2);
        linkedList.print();
        System.out.println("=======================");
        Node node = linkedList.find(4);
        System.out.println(node);
        System.out.println("=======================");
    }

    private static class Node{
        int value;
        Node next;

        public Node(int value) {
            this.value = value;
            this.next = null;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "value=" + value +
                    ", next=" + next +
                    '}';
        }
    }
}
